<template>
  <div class="login-container">
    <div class="login-content">
      <el-card class="login-card">
        <template #header>
          <div class="card-header">
            <h2>用户登录</h2>
            <p class="subtitle">登录您的账号，开始创建表情包</p>
          </div>
        </template>

        <el-form :model="formData" :rules="rules" ref="loginForm" label-position="top">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>

          <div class="form-actions">
            <el-button type="primary" @click="handleLogin" :loading="loading" size="large">
              登录
            </el-button>
            <router-link to="/register" class="register-link">
              没有账号？立即注册
            </router-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const API_BASE_URL = 'http://localhost:5000'
const router = useRouter()
const loginForm = ref(null)
const loading = ref(false)

const formData = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!formData.value.username || !formData.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    const response = await fetch('http://localhost:5000/api/user/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    const data = await response.json()
    console.log('Login response:', data)

    if (!response.ok) {
      throw new Error(data.message || `HTTP error! status: ${response.status}`)
    }

    if (data.status === 'success') {
      const { token, user_id, username } = data.data
      
      // 清除旧数据
      localStorage.clear()
      
      // 保存新数据
      localStorage.setItem('token', token)
      localStorage.setItem('userId', user_id)
      localStorage.setItem('username', username)
      
      // 验证数据是否正确保存
      console.log('Saved data:', {
        token: localStorage.getItem('token'),
        userId: localStorage.getItem('userId'),
        username: localStorage.getItem('username')
      })

      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(data.message || '登录失败')
    }
  } catch (error) {
    console.error('Login error:', error)
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e0f2ff 0%, #f5f7fa 100%);
}

.login-content {
  width: 100%;
  max-width: 500px;
  padding: 20px;
}

.login-card {
  border-radius: 8px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin-bottom: 8px;
  color: var(--primary-color);
}

.subtitle {
  color: var(--info-color);
  margin-top: 0;
}

.form-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.el-button {
  width: 100%;
}

.register-link {
  color: var(--primary-color);
  text-decoration: none;
}

.register-link:hover {
  text-decoration: underline;
}
</style>